package longrise.phone.com.bjjt_henan.compensate;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.LFView;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.CodeCountHelper;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.main.ServiceCenterView;
import longrise.phone.com.bjjt_henan.widget.PromptDialog;

/**
 * 生成协议书，Created by Administrator on 2016/5/12.
 */

public class CreateAgreementView extends LFView implements View.OnClickListener, MainActivity.OnActivityReturnBitmap {
    private Context context = null;
    private View view = null;
    private Button bt_createappointmen1;
    private Dialog processDialog;
    private BaseApplication mApplication;
    private Button bt_createappointmen2;
    private TextView tv_createagreement1;
    private TextView tv_createagreement2;
    private TextView tv_createagreement3;
    private TextView tv_createagreement4;
    private TextView tv_createagreement5;
    private TextView tv_createagreement6;
    private TextView tv_createagreement7;
    private TextView tv_createagreement8;
    private TextView tv_createappointment1;
    private TextView tv_createappointment2;
    private EntityBean[] CreateAgreementbean;
    private String appCaseno;
    private EditText et_createagreement1;
    private EditText et_createagreement2;
    private String dutytype2;
    // 本方请求签名
    private static final int SIDE_REQUEST_CODE = 0x0011;
    // 对方请求签名
    private static final int OHER_REQUEST_CODE = 0x0022;
    private String dutytype1;
    private LinearLayout hn_btn_back;
    private TextView tv_title;
    private TextView ll_driver_sign_he;
    private TextView ll_driver_sign_me;
    private LinearLayout ll_signpic_me;
    private LinearLayout ll_signpic_he;
    private ImageView iv_createagreement_he;
    private ImageView iv_createagreement_me;
    private ImageView iv_deletesign_he;
    private ImageView iv_deletesign_me;
    private byte[] bitmapByte;
    private Bitmap bitmap;
    private Bitmap otherBitmap;
    private Bitmap ownBitmap;

    private CodeCountHelper otherHelper;

    private CodeCountHelper myHelper;

    private String type;//1表示无争议生成协议书；2表示有争议生成认定书

    public CreateAgreementView(Context c, EntityBean[] beans, String appCaseno) {
        super(c);
        this.context = c;
        this.mApplication = ((MainActivity) c).getAppData();
        this.CreateAgreementbean = beans;
        this.appCaseno = appCaseno;
        if (context instanceof MainActivity) {
            ((MainActivity) context).setOnActivityReturnBitmap(this);
        }
    }

    public CreateAgreementView(Context c, EntityBean[] beans, String appCaseno, String type) {
        super(c);
        this.context = c;
        this.mApplication = ((MainActivity) c).getAppData();
        this.CreateAgreementbean = beans;
        this.appCaseno = appCaseno;
        this.type = type;
        if (context instanceof MainActivity) {
            ((MainActivity) context).setOnActivityReturnBitmap(this);
        }
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void refresh() {

    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);
    }

    private void initView() {
        view = View.inflate(context, R.layout.view_createagreementview, null);
        bt_createappointmen1 = (Button) view.findViewById(R.id.bt_createappointmen1);
        bt_createappointmen2 = (Button) view.findViewById(R.id.bt_createappointmen2);
        tv_createappointment1 = (TextView) view.findViewById(R.id.tv_createappointment1);
        tv_createappointment2 = (TextView) view.findViewById(R.id.tv_createappointment2);
        //对方数据
        tv_createagreement1 = (TextView) view.findViewById(R.id.tv_createagreement1);
        tv_createagreement2 = (TextView) view.findViewById(R.id.tv_createagreement2);
        tv_createagreement3 = (TextView) view.findViewById(R.id.tv_createagreement3);
        tv_createagreement4 = (TextView) view.findViewById(R.id.tv_createagreement4);
        //本方数据
        tv_createagreement5 = (TextView) view.findViewById(R.id.tv_createagreement5);
        tv_createagreement6 = (TextView) view.findViewById(R.id.tv_createagreement6);
        tv_createagreement7 = (TextView) view.findViewById(R.id.tv_createagreement7);
        tv_createagreement8 = (TextView) view.findViewById(R.id.tv_createagreement8);
        ll_driver_sign_he = (TextView) view.findViewById(R.id.ll_driver_sign_he);//对方驾驶员签名button
        ll_driver_sign_me = (TextView) view.findViewById(R.id.ll_driver_sign_me);//本方驾驶员签名button
        ll_signpic_he = (LinearLayout) view.findViewById(R.id.ll_signpic_he);//对方驾驶员签名图片布局
        ll_signpic_me = (LinearLayout) view.findViewById(R.id.ll_signpic_me);//本方驾驶员签名图片布局
        iv_createagreement_he = (ImageView) view.findViewById(R.id.iv_createagreement_he);//本方驾驶员签名图片
        iv_createagreement_me = (ImageView) view.findViewById(R.id.iv_createagreement_me);//本方驾驶员签名图片
        iv_deletesign_he = (ImageView) view.findViewById(R.id.iv_deletesign_he);//对方驾驶员签名图片删除
        iv_deletesign_me = (ImageView) view.findViewById(R.id.iv_deletesign_me);//本方驾驶员签名图片删除
        et_createagreement1 = (EditText) view.findViewById(R.id.et_createagreement1);
        et_createagreement2 = (EditText) view.findViewById(R.id.et_createagreement2);
        hn_btn_back = (LinearLayout) view.findViewById(R.id.hn_btn_back);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        if (TextUtils.equals(type, "1")) {
            tv_title.setText("生成协议书");
            bt_createappointmen1.setText("认可并提交生成事故责任协议书");
        } else {
            tv_title.setText("生成认定书");
            bt_createappointmen1.setText("认可并提交生成事故责任认定书");
        }

        EntityBean otherBean = null;//对方信息
        EntityBean myBean = null;//我的信息

        for (int i = 0; i < CreateAgreementbean.length; i++) {
            String ownother = CreateAgreementbean[i].getString("party");
            if (TextUtils.equals(ownother, "1")) {
                myBean = CreateAgreementbean[i];
            } else if (TextUtils.equals(ownother, "0")) {
                otherBean = CreateAgreementbean[i];
            }
        }
        //本方数据
        String carownphone1 = (String) myBean.get("carownphone");
        dutytype1 = (String) myBean.get("dutytype");
        String carownname1 = (String) myBean.get("carownname");
        //String id1 = (String)myBean.get("id");
        String casecarno1 = (String) myBean.get("casecarno");

        //对方数据
        String carownphone2 = (String) otherBean.get("carownphone");
        dutytype2 = (String) otherBean.get("dutytype");
        String carownname2 = (String) otherBean.get("carownname");
        //String id2 = (String)otherBean.get("id");
        String casecarno2 = (String) otherBean.get("casecarno");

        if ("0".equals(dutytype1)) {
            tv_createagreement5.setText("全责");
            tv_createagreement1.setText("无责");
        }
        if ("1".equals(dutytype1)) {
            tv_createagreement5.setText("无责");
            tv_createagreement1.setText("全责");
        }
        if ("2".equals(dutytype1)) {
            tv_createagreement5.setText("同责");
            tv_createagreement1.setText("同责");
        }
        if ("3".equals(dutytype1)) {
            tv_createagreement5.setText("主责");
            tv_createagreement1.setText("次责");
        }
        if ("4".equals(dutytype1)) {
            tv_createagreement5.setText("次责");
            tv_createagreement1.setText("主责");
        }
        tv_createagreement6.setText(carownname1);
        tv_createagreement2.setText(carownname2);
        tv_createagreement7.setText(casecarno1);
        tv_createagreement3.setText(casecarno2);
        tv_createagreement8.setText(carownphone1);
        tv_createagreement4.setText(carownphone2);

    }

    private void regEvent(boolean b) {
        if (null != bt_createappointmen1) {
            bt_createappointmen1.setOnClickListener(b ? this : null);
        }
        if (null != bt_createappointmen2) {
            bt_createappointmen2.setOnClickListener(b ? this : null);
        }
        if (null != tv_createappointment1) {
            tv_createappointment1.setOnClickListener(b ? this : null);
        }
        if (null != tv_createappointment2) {
            tv_createappointment2.setOnClickListener(b ? this : null);
        }
        if (null != hn_btn_back) {
            hn_btn_back.setOnClickListener(b ? this : null);
        }
        if (null != ll_driver_sign_he) {
            ll_driver_sign_he.setOnClickListener(b ? this : null);
        }
        if (null != ll_driver_sign_me) {
            ll_driver_sign_me.setOnClickListener(b ? this : null);
        }
        if (null != iv_deletesign_he) {
            iv_deletesign_he.setOnClickListener(b ? this : null);
        }
        if (null != iv_deletesign_me) {
            iv_deletesign_me.setOnClickListener(b ? this : null);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_createappointmen1:
                if (TextUtils.isEmpty(et_createagreement1.getText().toString().trim())) {
                    UiUtil.showToast(context, "请填写乙方验证码");
                    return;
                }
                if (null == otherBitmap) {
                    UiUtil.showToast(context, "请乙方驾驶员签名");
                    return;
                }
                if (TextUtils.isEmpty(et_createagreement2.getText().toString().trim())) {
                    UiUtil.showToast(context, "请填写甲方验证码");
                    return;
                }
                if (null == ownBitmap) {
                    UiUtil.showToast(context, "请甲方驾驶员签名");
                    return;
                }
                submitCreateArg();//生成事故责任认定
                break;
            case R.id.bt_createappointmen2:
//                //报警
//                showReportDialog();
                ServiceCenterView view = new ServiceCenterView(context, appCaseno);
                FrameworkManager.getInstance().showNewForm(context, view);
                break;
            case R.id.tv_createappointment1:
                String hisPhone = tv_createagreement4.getText().toString().trim();
                getCode(hisPhone, 1);//对方获取验证码
                break;
            case R.id.tv_createappointment2:
                String myPhone = tv_createagreement8.getText().toString().trim();
                getCode(myPhone, 0);//本方获取验证码
                break;
            case R.id.ll_driver_sign_he:
                // 对方签名
                // 跳转到签名的activity
                Intent intent3 = new Intent(context, SignatureActivity.class);
                if (context instanceof MainActivity) {
                    ((MainActivity) context).startActivityForResult(intent3,
                            OHER_REQUEST_CODE);
                }

                break;
            case R.id.ll_driver_sign_me:
                // 本方签名
                Intent intent1 = new Intent(context, SignatureActivity.class);
                if (context instanceof MainActivity) {
                    ((MainActivity) context).startActivityForResult(intent1,
                            SIDE_REQUEST_CODE);
                }
                break;
            case R.id.iv_deletesign_he:
                ll_driver_sign_he.setVisibility(View.VISIBLE);//button显示
                ll_signpic_he.setVisibility(View.GONE);
                otherBitmap = null;
                break;
            case R.id.iv_deletesign_me:
                ll_driver_sign_me.setVisibility(View.VISIBLE);//button显示
                ll_signpic_me.setVisibility(View.GONE);
                ownBitmap = null;
                break;
            case R.id.hn_btn_back:
                OnDestroy();
                closeForm();
                break;
        }
    }

    private PromptDialog dialog;

    private void showReportDialog() {
        if (null == dialog) {
            String title = context.getString(R.string.insurance_wait);
            dialog = new PromptDialog(context);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setConfirm("确定", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    telAlarm();
                }
            });
            dialog.setCancel("取消", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.setTitleNoIcon(title);
            dialog.setInfo(context.getString(R.string.call_content));
        }
        dialog.show();
    }

    //电话报警
    private void telAlarm() {
        BaseApplication application = ((MainActivity) context).getAppData();
        String uid = application.getKckpName();
        String token = application.getToken();
        DialogUtils.showDialog(context);
        ApiImpI.getInstance(context).telAlarm(uid, token, appCaseno, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                DialogUtils.closeDialog();
                if (!TextUtils.isEmpty(error)) {
                    UiUtil.showToast(context, error);
                }
            }

            @Override
            public void onSuccess(Object result) {
                DialogUtils.closeDialog();
                if (null == view) {
                    return;
                }
                EntityBean bean = (EntityBean) result;
                String restate = bean.getString("restate");
                String redes = bean.getString("redes");
                if (TextUtils.equals(restate, "1")) {
                    ((MainActivity) context).backToMainView();

                    checkPhone();
                } else {
                    if (!TextUtils.isEmpty(redes)) {
                        UiUtil.showToast(context, redes);
                    }
                }
            }
        });
    }

    //打电话
    private void checkPhone() {
        //拨号界面
        Uri uri = Uri.parse("tel:110");
        Intent intent = new Intent(Intent.ACTION_DIAL, uri);
        context.startActivity(intent);
    }

    //提交生成协议书
    private void submitCreateArg() {
        processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
        EntityBean bean = new EntityBean();
        EntityBean[] casecarlist = null;//车主信息数组
        EntityBean userinfo = mApplication.getLoginInfo().getBean("userinfo");
        bean.set("appcaseno", appCaseno);
        bean.set("ownsig", CommontUtils.Bitmap2Bytes(ownBitmap));//己方签名
        bean.set("othersig", CommontUtils.Bitmap2Bytes(otherBitmap));//对方签名

        EntityBean bean1 = new EntityBean();
        bean1.set("appcaseno", appCaseno);
        bean1.set("appphone", userinfo.getString("mobilephone"));
        bean1.set("casehaptime", CommontUtils.getNowTime());
        bean1.set("accidentplace", mApplication.getAddress());
        bean.set("kcbean", bean1);//案件信息，EntityBean

        EntityBean bfBean = new EntityBean();// 本方数据
        bfBean.set("carownname", tv_createagreement6.getText().toString().trim());
        bfBean.set("carownphone", tv_createagreement8.getText().toString().trim()); //手机号
        bfBean.set("casecarno", tv_createagreement7.getText().toString().trim()); // 案件车牌号
        bfBean.set("code", et_createagreement2.getText().toString().trim()); // 验证码
        bfBean.set("dutytype", dutytype1);//责任类型

        EntityBean dfBean = new EntityBean();// 对方数据
        dfBean.set("carownname", tv_createagreement2.getText().toString().trim());
        dfBean.set("carownphone", tv_createagreement4.getText().toString().trim()); //手机号
        dfBean.set("casecarno", tv_createagreement3.getText().toString().trim()); // 案件车牌号
        dfBean.set("code", et_createagreement1.getText().toString().trim()); // 验证码
        dfBean.set("dutytype", dutytype2);//责任类型

        casecarlist = new EntityBean[]{bfBean, dfBean};
        bean.set("carbeans", casecarlist);
        bean.set("uid", mApplication.getKckpName());
        bean.set("token", mApplication.getToken());
        LoadDataManagerCar.getInstance(context).callService(null,
                mApplication.getServerUrl(), URLConstant.KCKPCREATERESPONIMG, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        String redes = bean.getString("redes");
                        if (!TextUtils.isEmpty(redes)) {
                            UiUtil.showToast(context, redes);
                        }
                        if ("1".equals(restate)) {
                            InsuranceReportChoiceView insurancereportchoiceview = new InsuranceReportChoiceView(context, CreateAgreementbean, appCaseno);
                            FrameworkManager.getInstance().showNewForm(context, insurancereportchoiceview);
                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(context, "连接超时，请检查网络后重试。");
                        } else if (resultType == LoadDataManagerFather.ResultType.NoNetWorks) {
                            UiUtil.showToast(context, "无网络连接，请检查您的网络");
                        }
                        return;
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                    }
                });
    }

    /**
     * 获取验证码
     */
    public void getCode(String phonenum, final int flag) {
        if (!StringUtils.isPhone(phonenum)) {
            Toast.makeText(context, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        DialogUtils.showDialog(context);
        ApiImpI.getInstance(context.getApplicationContext()).getAgreementCode(phonenum, "4", new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                DialogUtils.closeDialog();
            }

            @Override
            public void onSuccess(Object result) {
                DialogUtils.closeDialog();
                EntityBean bean = (EntityBean) result;
                String redes = bean.getString("redes");
                if (!TextUtils.isEmpty(redes)) {
                    UiUtil.showToast(getContext(), redes);
                }
                String restate = bean.getString("restate");
                if (TextUtils.equals(restate, "1")) {
                    if (null == view) {
                        return;
                    }
                    if (flag == 0) {//己方
                        if (null == myHelper) {
                            myHelper = new CodeCountHelper(tv_createappointment2);
                        }
                        myHelper.startCount();
                    } else if (flag == 1) {//对方
                        if (null == otherHelper) {
                            otherHelper = new CodeCountHelper(tv_createappointment1);
                        }
                        otherHelper.startCount();
                    }
                }
            }
        });
    }

    @SuppressLint("NewApi")
    @Override
    public void activityReturnBitmap(int requestCode, int resultCode,
                                     Intent data) {
        if (resultCode == MainActivity.RESULT_OK) {
            bitmapByte = data.getByteArrayExtra("bitmap");
            bitmap = BitmapFactory.decodeByteArray(bitmapByte, 0,
                    bitmapByte.length);
            Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);
            if (requestCode == SIDE_REQUEST_CODE) {
                // 本方签名完成回调函数
                if (bitmap != null) {
                    //隐藏本方的button，显示签名布局，本方签名bitmap转String
                    ll_driver_sign_me.setVisibility(View.GONE);
                    ll_signpic_me.setVisibility(View.VISIBLE);
                    iv_createagreement_me.setBackground(drawable);
                    ownBitmap = bitmap;
                }
            } else if (requestCode == OHER_REQUEST_CODE) {
                // 对面签名完成回调函数
                if (bitmap != null) {
                    ll_driver_sign_he.setVisibility(View.GONE);
                    ll_signpic_he.setVisibility(View.VISIBLE);
                    iv_createagreement_he.setBackground(drawable);
                    otherBitmap = bitmap;
                }
            }
        }
        // 清除bitmap byte数据
        bitmapByte = null;
    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        if (null != bitmap) {
            bitmap.recycle();
            bitmap = null;
        }
        if (null != dialog) {
            dialog = null;
        }
        if (null != myHelper) {
            myHelper.destroy();
            myHelper = null;
        }
        if (null != otherHelper) {
            otherHelper.destroy();
            otherHelper = null;
        }
        processDialog = null;
        view = null;
    }

}
